package Servlet;

import com.alibaba.fastjson.JSON;
import entity.Man;
import service.impl.studentDaoserviceimpl;
import service.studentDaoservice;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/Studentservlet")
public class studentservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        studentDaoservice obj = new studentDaoserviceimpl();
        List<Man> list = obj.getAll();
        String man= JSON.toJSONString(list);
        out.print(man);

        String opr = req.getParameter("opr");
        if("addStudent".equals(opr)){
            String name = req.getParameter("name");
            int age = Integer.parseInt(req.getParameter("age"));
            String mojor = req.getParameter("mojor");
            int addHs =obj.addStudent(name,age,mojor);
            String sc=req.getContextPath();
            if (addHs>0){
                out.print("<script>alert('新增成功')</script>");
                resp.sendRedirect(sc+"/index.jsp");
            }
        }
        else if("deleteStudent".equals(opr)){
            int did = Integer.parseInt(req.getParameter("did"));
            int deleths = obj.deleteStudent(did);
            String sc=req.getContextPath();
            if (deleths>0){
                out.print("<script>alert('删除成功')</script>");
                resp.sendRedirect(sc+"/index.jsp");
            }

            else if ("updateStudent".equals(opr)) {
                int id2 = Integer.parseInt(req.getParameter("upid"));
                String name2 = req.getParameter("upname");
                int age2 = Integer.parseInt(req.getParameter("upage"));
                String mojor2 = req.getParameter("upmojor");
                int uphs = obj.updateStudent(id2,name2, age2, mojor2);
                String ac=req.getContextPath();
                if (uphs>0){
                    out.print("<script>alert('修改成功')</script>");
                    resp.sendRedirect(ac+"/index.jsp");
                }
            }
        }
    }
}


